<?php
namespace Ucmaim\Model;
use Think\Model;


class OrderModel extends Model{
    public function NewOrder(){
        if ( IS_POST ) {
            $_POST['order_status'] = 1;
            $_POST['order_time'] = time();
            $this->create();
            $result = $this->add();
            return $result;
        }
    }

    //由订单sn查询订单信息
    public function getOrderInfo($sn, $extra = false){
        $this->_orderFieldsInit();
        $map['order_sn'] = $sn;
        $data = $this->where($map)->find();
        if(empty($data)) return [];
        // 获取卖家支付宝账号
        $data['seller_alipay'] = $this->getSellerAlipay($sn);
        if(true === $extra) {
            $Category = D('GoodsCategory');
            $map['goods_id'] = $data['goods_id'];
            $goods = M('Goods')->where($map)->find();
            $relation = $Category->getOne($goods['gc_id']);
            $relation = D('GoodsCategory')->getRelation($relation);
            $data['relation'] = $relation['goods_relation'];
        }
        return $data;
    }

    /**
     * 更改订单状态
     *  ->  0 订单已完成
     *  ->  1 等待买家付款
     *  ->  2 买家已付款，等待发货
     *  ->  3 卖家已发货
     *  ->  4 买家已确认收货 (打款给卖家)
     *  -> -4 买家申请退款  (打款给买家)
     *  -> -3 确认收货超时
     *  -> -2 发货超时
     *  -> -1 订单取消
     *
     *
     * @param $order_sn
     * @param $status
     * @param $remark
     * @param $time
     * @return bool
     */
    public function updateOrderStatus($order_sn, $status, $remark = ''){
        $data['order_status']  = (int)$status;
        $map['order_sn'] = $order_sn;
        $remark = trim($remark);
        if('' !== $remark){
            $data['order_remark'] = $remark;
        }
        // 更新状态时间
        if( $data['order_status'] === 2 ){
            $data['pay_time'] = time();
        }elseif( $data['order_status'] === 3 ){
            $data['send_time'] = time();
        }elseif( $data['order_status'] === 4 ){
            $data['confrim_time'] = time();
        }

        $result = $this->where($map)->save($data);
        return $result;
}

    // 获取订单列表
    public function get($member_id = 0, $who = 'buyer' , $status = '', $map = []){
        $order_status_list = C('ORDER_STATUS');

        $who = strtolower($who);
        $this->_orderFieldsInit();
        switch($who){
            case 'seller':
                $map['A.seller_id'] = $member_id;
                break;
            case 'buyer':
                $map['A.buyer_id'] = $member_id;
                break;
            case 'all':
            default:
                $map = [];
                break;
        }

        $data = $this->where($map)->select();
        $Category = D('GoodsCategory');
        $Goods    = M('Goods');
        $map = [];
        $result = [];

        foreach( $data as $k => $v ){
            if(isset($order_status_list[$status]) && $status != $v['order_real_status']) continue;
            $map['goods_id'] = $v['goods_id'];
            $goods = $Goods->where($map)->find();
            $relation = $Category->getOne($goods['gc_id']);
            $relation = D('GoodsCategory')->getRelation($relation);
            $v['goods_relation'] = $relation['goods_relation'];
            $result[] = $v;
        }



        return $result;
    }


    /**
     * 判断是否超时
     */
   private function _getTime($data){
       $now_time = time();
       $config = getConfig();

       switch($data['order_status']){
           case 1:
               $deadline = $config['Paytime'];
               $start_time = $data['order_time'];
               break;
           case 2:
               $deadline = $config['deliverytime'];
               $start_time = $data['pay_time'];
               break;
           case 3:
               $deadline = $config['Receivingtime'];
               $start_time = $data['send_time'];
               break;
           Default:
               $this->getError();
               break;
       }

       if (($now_time - $start_time) < $deadline) {
           $data['time_out'] = 0;
           $data['end_time'] = $start_time + $deadline;
           $data['deadline'] = $data['end_time'] - $now_time;
       } else {
           $data['time_out'] = 1;
       };

       return $data;
   }

    // 查找可结算的订单
    public function settlementOrders($condition = []){
        // 结算给卖家，符合的订单状态有：4（买家已确认收货）, -3（确认收货超时），未更新状态（但实际是已确认超时）
        $condition['status'] = [-3, 4];
        if($condition['sn']){
            return $this->getAllOrders($condition)[0];
        }
        return $this->getAllOrders($condition);
    }

    // 后台获取全部订单列表
    public function getAllOrders($condition = [], $page = 0, $pageSize = 0){
        if( !empty($condition) && is_array($condition)){
            $where = '';
            if( $condition['sn'] ){
                $where .= " order_sn = '{$condition['sn']}'";
            }

            if( $condition['buyer'] ){
                $where .=  '' === $where ? " buyer_name = '{$condition['buyer']}'" :  " AND buyer_name = '{$condition['buyer']}'";
            }

            if( $condition['seller'] ){
                $where .=  '' === $where ?  " seller_name = '{$condition['seller']}'" :  " AND seller_name = '{$condition['seller']}'";
            }

            if( $condition['date'] ){
                $tmp = explode('~', $condition['date']);
                $start_date = trim($tmp[0]);
                $end_date   = trim($tmp[1]);
                $start = strtotime($start_date);
                $end   = strtotime($end_date) + 86400;  //end需要加一天，防止当天的数据搜索不出来
                $where .= '' === $where ? " order_time > $start AND order_time < $end" : " AND order_time > $start AND order_time < $end";
            }

            if( $condition['status'] ){
                $in = '(' . implode(',', $condition['status']) . ')';
                $where .= '' === $where ? ' order_real_status IN ' . $in : ' AND order_real_status IN ' . $in;
            }
            if( $where === '' ) return $this->getAllOrders([], $page, $pageSize);
            $this->_orderFieldsInit();
            $tempSql = $this->fetchSql(true)->select();
            $total = $this->query("SELECT COUNT(*) FROM ($tempSql) AS _T WHERE $where");
            $total = (int)$total[0][ 'count(*)'];

            if( $total === 0 ) return [];
            if( $page > 0 && $pageSize > 0 ){
                $offset = $pageSize * $page - $pageSize;
                $limit  = " LIMIT $offset, $pageSize";
                return array('total'=> $total, 'data' => $this->query("SELECT * FROM ($tempSql) AS _T WHERE $where ORDER BY order_time desc $limit"));
            }else{
                return $this->query("SELECT * FROM ($tempSql) AS _T WHERE $where ORDER BY order_time desc");
            }
        }else{
            $this->alias('A')
                ->join('uc_member B on A.seller_id = B.member_id')
                ->join('uc_member C on A.buyer_id = C.member_id')
                ->join('uc_goods D on A.goods_id = D.goods_id')
                ->order('order_time asc');
            $total = $this->count();
            if( $total === 0 ) return array('total' => $total, 'data' => []);
            $this->_orderFieldsInit();
            if( $page > 0 && $pageSize > 0  ){
                $this->page($page, $pageSize);
                return array('total'=> $total, 'data' => $this->select());
            }
            return $this->select();
        }
    }

    // 完成订单打款操作， 1.更新订单状态；2.增加卖家的资金流水；3.扣除商品的库存
    public function _balance($order_info ){
        $Log   = D('MoneyLog');
        $Goods = D('Goods');
        $this->startTrans();
        // 更新订单状态至完成
        $r1 = $this->updateOrderStatus($order_info['order_sn'], 0);
        // 增加卖家资金流水
        $remark = '交易完成';
        $r2 = $Log->makeLog($order_info['seller_id'], $order_info['buyer_id'], order_balance($order_info['order_number'], $order_info['order_price']), $order_info['order_sn'], '', $remark);
        // 扣除商品库存
        $r3 = $Goods->changeStorage($order_info['goods_id'], $order_info['order_number'], 'reduce');
        if($r1 && $r2 && $r3){
            $this->commit();
            return true;
        }else{
            $this->rollback();
            return false;
        }
    }

    // 通过订单号获取卖家的支付宝账号
    public function getSellerAlipay($order_sn){
        $map['A.order_sn'] = $order_sn;
        $result = $this->alias('A')->field('B.goods_alipay')->join('uc_goods B on A.goods_id = B.goods_id')->where($map)->find();
        return $result['goods_alipay'] ? $result['goods_alipay'] : '';
    }

    // 初始化字段订单返回字段（返回计算后的实时状态<order_real_status>，包括操作超时）
    private function _orderFieldsInit(){
        $configures = getConfig();
        $expire = [
            'send' => $configures['SEND_EXPIRE'],       //发货超时时间
            'pay'  => $configures['PAY_EXPIRE'],        //支付超时时间
            'confirm' => $configures['CONFIRM_EXPIRE'], //确认收货超时
        ];
        $time = time();
        $this->alias('A')
            ->field("A.*,
                CASE WHEN B.member_name = '' THEN B.member_mobile ELSE B.member_name END AS seller_name,
                CASE WHEN C.member_name = '' THEN C.member_mobile ELSE C.member_name END AS buyer_name,
                CASE WHEN A.order_time + {$expire['pay']}  < $time AND A.order_status = 1 THEN -5
                     WHEN A.pay_time + {$expire['send']}  < $time AND A.order_status = 2 THEN -2
                     WHEN A.send_time + {$expire['confirm']}  < $time AND A.order_status = 3 THEN -3
                     WHEN A.order_status = 0 THEN 0
                     WHEN A.order_status = 1 THEN 1
                     WHEN A.order_status = 2 THEN 2
                     WHEN A.order_status = 3 THEN 3
                     WHEN A.order_status = 4 THEN 4
                     WHEN A.order_status = -1 THEN -1
                     WHEN A.order_status = -2 THEN -2
                     WHEN A.order_status = -3 THEN -3
                     WHEN A.order_status = -4 THEN -4
                     WHEN A.order_status = -5 THEN -5 END AS order_real_status,
                D.goods_title
                ")
            ->join('uc_member B on A.seller_id = B.member_id')
            ->join('uc_member C on A.buyer_id = C.member_id')
            ->join('uc_goods D on A.goods_id = D.goods_id')
            ->order('order_time desc');
    }



}